package cxm.proj.xtalk.smack;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import cxm.lib.util.MyLog;

// upload ftp file with background servcie
@SuppressLint("HandlerLeak")
public class FtpUploadService extends Service {
    FTPClient client = null;
	private Looper mServiceLooper;
	private ServiceHandler mServiceHandler;
	String host = null;
	String name = null;
	String pass = null;
	String file = null;
	String upFolder = null;

	// Handler that receives messages from the thread
	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			// construct ftp client
			try {
				client.connect(host,21);
				client.login(name, pass);
				client.setType(FTPClient.TYPE_BINARY);
				client.changeDirectory(upFolder);
				File uploadFile = new File(file);
				client.upload(new File(file), new MyTransferListener());
				// delete file
				uploadFile.delete();
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot start ftp upload: " + e);
			}
		}
	}
	@Override
	public void onCreate() {
	    client = new FTPClient();

		// Start up the thread running the service.  Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.  We also make it
		// background priority so CPU-intensive work will not disrupt our UI.
		HandlerThread thread = new HandlerThread("ServiceStartArguments");
		thread.start();

		// Get the HandlerThread's Looper and use it for our Handler 
		mServiceLooper = thread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// get ftp params
		host = intent.getStringExtra("host");
		name = intent.getStringExtra("name");
		pass = intent.getStringExtra("pass");
		file = intent.getStringExtra("file");
		upFolder = intent.getStringExtra("upfolder");
		if (null == host || null == name ||
				null == pass || null == file)
			throw new IllegalStateException("argument null");
		
		// For each start request, send a message to start a job and deliver the
		// start ID so we know which request we're stopping when we finish the job
		Message msg = mServiceHandler.obtainMessage();
		msg.arg1 = startId;
		mServiceHandler.sendMessage(msg);

		// If we get killed, after returning from here, restart
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// We don't provide binding, so return null
		return null;
	}

	@Override
	public void onDestroy() {
	}
	
	public class MyTransferListener implements FTPDataTransferListener {
		public void started() {
			MyLog.Log(MyLog.Level.Debug, "Transfer file started");
		}

		public void transferred(int length) {
		}

		public void completed() {
			MyLog.Log(MyLog.Level.Info, "Transfer file completed");
			Toast.makeText(FtpUploadService.this, "Upload completed",
					Toast.LENGTH_LONG).show();
			try {
				client.logout();
				client.disconnect(true);
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot disconnect FTP server: " + e);
			}
			
			FtpUploadService.this.stopSelf();
		}

		public void aborted() {
			MyLog.Log(MyLog.Level.Error, "Transfer file aborted");
			Toast.makeText(FtpUploadService.this, "Upload aborted",
					Toast.LENGTH_LONG).show();
			try {
				client.logout();
				client.disconnect(true);
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot disconnect FTP server: " + e);
			}
			
			FtpUploadService.this.stopSelf();
		}

		public void failed() {
			MyLog.Log(MyLog.Level.Error, "Transfer file failed");
			Toast.makeText(FtpUploadService.this, "Upload failed",
					Toast.LENGTH_LONG).show();
			try {
				client.logout();
				client.disconnect(true);
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot disconnect FTP server: " + e);
			}
			
			FtpUploadService.this.stopSelf();
		}
	}
}
